package com.briup.web.servlet;

import com.briup.bean.Customer;
import com.briup.bean.ShopCar;
import com.briup.service.IShopCarService;
import com.briup.service.impl.IShopCarServiceImpl;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.Currency;
import java.util.List;

/**
 * @author 王若龙
 * @CreateTime 2022-09-26 11:10
 */
@WebServlet("/shopCarAdd")
public class ShopCarAddServlet extends HttpServlet {

    private IShopCarService shopCarService = new IShopCarServiceImpl();

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        int num = Integer.parseInt(req.getParameter("num"));
        int bookId = Integer.parseInt(req.getParameter("bookId"));
        String id = req.getParameter("customerId");
        try {
            if (StringUtils.isEmpty(id)) {
                throw new RuntimeException("用户未登录");
            }
            int customerId = Integer.parseInt(id);
            ShopCar shopCar = new ShopCar(num, bookId, customerId);
            shopCarService.saveShopCar(shopCar);
        } catch (RuntimeException e) {
            e.printStackTrace();
            req.getSession().setAttribute("error", e.getMessage());
        } finally {
            resp.sendRedirect("viewBook.jsp");
        }
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        HttpSession session = req.getSession();
        Customer customer = (Customer)session.getAttribute("customer");
        try {
            if (customer == null){
                throw new RuntimeException("用户未登录");
            }
            double num=0;
            int id = customer.getId();
            List<ShopCar> shopCarsByCustomer = shopCarService.findShopCarsByCustomer(id);
            for (ShopCar shopCar : shopCarsByCustomer) {
                num += shopCar.getBook().getPrice() * shopCar.getNum();
            }
            session.setAttribute("shopCars", shopCarsByCustomer);
            session.setAttribute("length", shopCarsByCustomer.size());
            session.setAttribute("allPrice", num);
        }catch (Throwable t){
            t.printStackTrace();
            session.setAttribute("error", t.getMessage());
        }finally {
            resp.sendRedirect("/shopCart.jsp");
        }

    }
}
